package com.yy.app.controller;

import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.oauth2.core.oidc.user.OidcUser;
import org.springframework.security.oauth2.core.user.OAuth2User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Collections;
import java.util.Map;

/**
 * @Description
 * @Date 2025/10/10 上午10:20
 * @Author yanglin
 **/
@Controller
public class HomeController {

    @GetMapping("/")
    public String home(@AuthenticationPrincipal OidcUser authentication, Model model) {
        if (authentication != null) {
            model.addAttribute("userName", authentication.getName());
            model.addAttribute("authorities", authentication.getAuthorities());
            model.addAttribute("userAttributes", authentication.getAttributes());
            model.addAttribute("idToken", authentication.getIdToken().getTokenValue());
        }
        return "index";
    }

    @GetMapping("/login")
    public String login() {
        return "login";
    }


    @GetMapping("/secured")
    public String secured(@AuthenticationPrincipal OidcUser authentication, Model model) {
        if (authentication != null) {
            model.addAttribute("userName", authentication.getName());
            model.addAttribute("authorities", authentication.getAuthorities());
            model.addAttribute("userAttributes", authentication.getAttributes());
            model.addAttribute("idToken", authentication.getIdToken().getTokenValue());
        }
        return "secured";
    }
    /**
     * 添加用户信息端点
     * @param principal
     * @return
     */
    @GetMapping("/userinfo")
    @ResponseBody
    public Map<String, Object> userInfo(@AuthenticationPrincipal OAuth2User principal) {
        if (principal != null) {
            return principal.getAttributes();
        }
        return Collections.singletonMap("error", "用户未登录");
    }
}
